package club.banyuan.service;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author edz
 * @version 1.0
 * @date 2020/12/20 上午10:11
 */
public class PageService {
//    private DataOutputStream dos;
    /**
     * 向页面发送状态码和数据
     */
    public <T> void sendData(T t,DataOutputStream dos) throws IOException {
        sendData(t,true,dos);
    }
    public static  <T> void sendData(T t,boolean success,DataOutputStream dos) throws IOException {
        if(success){
            dos.writeBytes("HTTP/1.1 200 OK\n");
        }else{
            dos.writeBytes("HTTP/1.1 400 bad_request\n");
        }
        Map<String,T> respondMap= new HashMap<String, T>();
        respondMap.put("data",t);
        //把t转换成json字符串的形式写给页面
        String responseJson = JSONObject.toJSONString(respondMap);
        System.out.println(responseJson);
        dos.writeBytes("Content-Type: application/json; charset=utf-8\n");
        dos.writeBytes("Content-Length: " + responseJson.getBytes().length + "\n");
        dos.writeBytes("\n");
        dos.write(responseJson.getBytes());
        dos.flush();
    }

    public PageService() {
    }
}
